package com.jczy.cyclone.widget.photoview

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.recyclerview.widget.RecyclerView

import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.DrawableImageViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.fenghongzhang.lib_net.model.Image
import com.fenghongzhang.module_main.R
import com.fenghongzhang.module_main.glide.glide.AliOssUrl
import com.fenghongzhang.module_main.glide.glide.GlideApp
import com.fenghongzhang.module_main.glide.pic.Info
import com.fenghongzhang.module_main.glide.pic.PhotoView



/**
 *@author Wcj
 *@description
 *@date 2022/7/5 16:27
 */
class PhotoViewPagerAdapter(
    private val picItems: List<Image>,
    private val picImageInfo: List<Info>?,
    private var startAnim: Boolean = true,
    private val onImageClick: (() -> Unit)? = null,
    private val onImageLongClick: ((Int) -> Unit)? = null
) :

    RecyclerView.Adapter<PhotoViewPagerAdapter.PhotoViewHolder>() {

    private lateinit var mContext: Context

    private var cancel:Boolean=false
    fun cancelLoadImage(cancel:Boolean){
        this.cancel=cancel

    }
    class PhotoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val pic: PhotoView = itemView.findViewById(R.id.pv)
        val ivPlay: ImageView = itemView.findViewById(R.id.iv_play)
        val pb = itemView.findViewById<ProgressBar>(R.id.contentLoadingProgressBar)

        init {
            pic.animaDuring=200
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder {
        mContext = parent.context
        return PhotoViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_photo_view_item, parent, false))
    }

    override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) {
        holder.apply {
            val mediaUrl = picItems[position].url
            //pb.visibility = if (mediaUrl.endsWith(".mp4")) View.GONE else View.VISIBLE
            if (mediaUrl.isEmpty()) {
                GlideApp.with(mContext)
                    .asBitmap()
                    .load(R.drawable.shape_bg_mask_round_4dp)
                    .into(holder.pic)
                return
            } else {
                if (mediaUrl.endsWith("gif")) {
                    loadGif(position)
                } else {
                    loadPic(position, holder)
                }
            }
            ivPlay.visibility = if (mediaUrl.endsWith(".mp4")) View.VISIBLE else View.GONE
            ivPlay.setOnClickListener {
             //   VideoPlayerActivity.jump(mediaUrl)
            }

            pic.enable()
            pic.enableRotate()
            itemView.setOnClickListener {
                onImageClick?.invoke()
            }
            pic.setOnClickListener {
                onImageClick?.invoke()
            }
        }
    }

    private fun PhotoViewHolder.loadGif(position: Int) {
        GlideApp.with(mContext)
            .asGif()
            .applyGif()
            .load(if (picItems[position].url.isEmpty()) "" else AliOssUrl(picItems[position].url))
            .placeholder(pic.drawable)
            .listener(object : RequestListener<GifDrawable> {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<GifDrawable>?, isFirstResource: Boolean): Boolean {
                    pb.visibility = View.GONE
                    return false
                }

                override fun onResourceReady(resource: GifDrawable?, model: Any?, target: Target<GifDrawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                    pb.visibility = View.GONE
                    picImageInfo?.apply {
                        if (startAnim) {
                            startAnim = false
                            pic.animaFrom(this[position])
                        }
                    }
                    return false
                }
            })
            .into(pic)
    }

    private fun PhotoViewHolder.loadPic(
        position: Int,
        holder: PhotoViewHolder
    ) {
        Log.d("PhotoViewPagerAdapter", "loadPic ${picItems[position]} ")
        if (startAnim && !picItems[position].thumbnailUrl.isNullOrEmpty()) {

            GlideApp.with(mContext)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .load(if (picItems[position].url.isEmpty()) "" else AliOssUrl(picItems[position].url))
                .preload()

            GlideApp.with(mContext)
                .load(picItems[position].thumbnailUrl)
                .applyPhotoView()
                .into(object : DrawableImageViewTarget(pic) {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        super.onResourceReady(resource, transition)
                        pic.setOnLongClickListener {
                            onImageLongClick?.invoke(holder.absoluteAdapterPosition)
                            return@setOnLongClickListener true
                        }
                        val width: Int = resource.intrinsicWidth ?: 1
                        val height: Int = resource.intrinsicHeight ?: 0
                        //图片宽高比大于手机比例，以长图的形式显示
                        if (height / width > 1.8) {
                            pic.scaleType = ImageView.ScaleType.FIT_START
                        } else {
                            pic.scaleType = ImageView.ScaleType.FIT_CENTER
                        }
                        pic.setImageDrawable(resource)
                        picImageInfo?.apply {
                            if (startAnim) {
                                startAnim = false
                                pic.animaFrom(this[position])
                            }
                        }

                        //加载原图
                        Handler(Looper.getMainLooper()).postDelayed({
                            if(!cancel)
                                loadOriginalImage(position, holder)
                        }, 300)
                    }
                })

        } else {
            loadOriginalImage(position, holder)
        }

    }

    private fun PhotoViewHolder.loadOriginalImage(position: Int, holder: PhotoViewHolder) {

        GlideApp.with(mContext)
            .asBitmap()
            .load(if (picItems[position].url.isEmpty()) "" else AliOssUrl(picItems[position].url))
            .applyPhotoView()
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadStarted(placeholder: Drawable?) {
                    Log.d("PhotoViewPagerAdapter", "onLoadStarted ${picItems[position]}")
                    pb.visibility = View.VISIBLE
                    super.onLoadStarted(placeholder)
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    Log.d("PhotoViewPagerAdapter", "onLoadFailed ${picItems[position]}")
                    super.onLoadFailed(errorDrawable)
                    pb.visibility = View.GONE
                }

                override fun onLoadCleared(placeholder: Drawable?) {

                }

                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    Log.d("PhotoViewPagerAdapter", "onResourceReady ${picItems[position]}")
                    //super.onResourceReady(resource, transition)
                    pb.visibility = View.GONE
                    pic.setOnLongClickListener {
                        onImageLongClick?.invoke(holder.absoluteAdapterPosition)
                        return@setOnLongClickListener true
                    }
                    val width: Int = resource.width ?: 1
                    val height: Int = resource.height ?: 0
                    // 图片宽高比大于手机比例，以长图的形式显示
                    if (height / width > 1.8) {
                        pic.scaleType = ImageView.ScaleType.FIT_START
                    } else {
                        pic.scaleType = ImageView.ScaleType.FIT_CENTER
                    }
                    if(!cancel){
                        pic.setImageBitmap(resource)
                    }
                    picImageInfo?.apply {
                        if (startAnim) {
                            startAnim = false
                            pic.animaFrom(this[position])
                        }
                    }
                }
            })
    }


    override fun getItemCount() = picItems.size
}